#include <sys/time.h>
#include "wait_response_list.h"
#include "global_val.h"

wait_res_node* head=NULL;
unsigned char WAIT_RES_ARRAY[256]; //为0代表对应的num已经被响应了，为1就是没有被响应。

void insert_node(char *pkg_mac, int cmd_type, unsigned char serial_number){
	wait_res_node *newNode;
	newNode = (wait_res_node *)malloc(sizeof(wait_res_node));
	memcpy(newNode->mac, pkg_mac, 8);
	newNode->cmd_type = cmd_type;
	newNode->serial_number = serial_number;
	gettimeofday(&(newNode->tv),NULL);//保存指令发生时间
	if(head==NULL)
	{
		newNode->next = NULL;
		head          = newNode;
	}
	else
	{	
		//printf("over insert\n");
		newNode->next = head;
		head          = newNode;
	}
}


void loop_wait_res_list(void){
	int count=0;
	char real_mac[32];
	
	//遍历未收到响应的链表，判断是否超时未响应
	if(head==NULL) return ;
	
	wait_res_node *p1 = head; 
	wait_res_node *p2 = head;//p2指向p1的上一个节点
	struct timeval tv;
	
	gettimeofday(&tv,NULL);//获取当前时间
	
	while(p1 != NULL)
	{
		//p2 = p1;
		//p1 = p1->next;
		//printf("bianli:%d\n", count++);
		if(WAIT_RES_ARRAY[p1->serial_number]==0 || (tv.tv_sec - p1->tv.tv_sec) > 1) //已经被响应过了
		{
			//printf("bianli:%d room_id:%d\n", count++, p1->room_id);
			if(p1==head)//删除的节点为头节点
			{
				head = p1->next; //要删除的是第一个节点 头节点要下移	
				p2   = p1->next;
			}
			else
			{
				p2->next=p1->next;
			}
			
			//printf("del->%d:%d\n", p1->serial_number, WAIT_RES_ARRAY[p1->serial_number]);
			
			if(WAIT_RES_ARRAY[p1->serial_number]!=0)//超时未响应
			{
				str_transition_mac(p1->mac, real_mac);
				server_msg_update(real_mac, p1->cmd_type);
				//printf("over time:%d\n", p1->room_id);
			}
			
			WAIT_RES_ARRAY[p1->serial_number]=0;
			
			free(p1);
			
			if(p2!=NULL)
			{
				p1=p2->next;
			}
			else
			{
				p1=NULL;
			}
			
		}
		else
		{
			p2=p1;
			p1=p1->next;
		}
	}
}

